package com.h2cloud.rolling;

/**
 * @author: wulongkai
 * @create: 2023-06-15 10:50
 **/

import lombok.Data;

import java.io.*;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;

public class SerializationExample {
    public static void main(String[] args) {
        // 创建原始对象
        MyClass originalObj = new MyClass();
        originalObj.setAges(25);
        originalObj.setName("longkai");


        try {
            // 将对象流化到字节数组中
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);
            oos.writeObject(originalObj);
            oos.flush();
            byte[] serializedObject = bos.toByteArray();

            // 创建新的对象
            MyClass newObj = new MyClass();

            // 从字节数组中反序列化并设置数据到新对象
            ByteArrayInputStream bis = new ByteArrayInputStream(serializedObject);
            ObjectInputStream ois = new ObjectInputStream(bis);
            MyClass deserializedObj = (MyClass) ois.readObject();

            // 使用反射将反序列化后的数据设置到新对象
            Field[] fields = MyClass.class.getDeclaredFields();
            for (Field field : fields) {
                field.setAccessible(true);
                Object value = field.get(deserializedObj);
                field.set(newObj, value);
            }

            // 打印新对象的属性
            System.out.println(newObj);
        } catch (IOException | ClassNotFoundException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}

// 示例类，实现了Serializable接口
@Data
class MyClass implements Serializable {
    private String name;
    private List<innerClass> ages;

    public MyClass() {
    }

    public void setAges(int age) {
        innerClass innerClass = new innerClass();
        innerClass.setAge(age);
        this.ages = Collections.singletonList(innerClass);
    }
}

@Data
class innerClass implements Serializable {
    int age;
}

